
// pages/shopCar/shopCar.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isEmbit: false, //是否编辑
    startX: 0, //开始坐标
    startY: 0,
    listData: [],  //懒加载区域
    topNum: 0,
    shopCar: [],  //购物车
    totalPrice: 0, //总价
    totalDisCount:0, //折扣价
    totalNum: 0, //总数
    selectedAllStatus: false, // 全选
    payShop: [], //购买的商品列表
  },
  // 获取滚动条的位置
  scrolltoupper: function (e) {
    let t = e.detail.scrollTop;
    if (t > 100 && !this.data.floorstatus) {
      // 避免重复setData
      this.setData({
        floorstatus: true
      })
    }
    if (t < 100 && this.data.floorstatus) {
      this.setData({
        floorstatus: false
      })
    }
  },
  // 回到顶部
  goTop: function (e) {
    this.setData({
      topNum: 0,
    })
  },
  // 完成
  func() {
    console.log(1)
    let status = this.data.isEmbit;
    status = !this.data.isEmbit;
    this.setData({
      isEmbit: status
    })
  },

  // 确认订单页
  toOrder() {
    let model = JSON.stringify(this.data.payShop);
    if (this.data.payShop != "") {
      wx.navigateTo({
        url: '/pages/shopCar/order/order?list=' + model,

      })
    }

  },
  // 数量减
  reduce(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.shopCar;
    let num = carts[index].num;
    if (num <= 1) {
      return
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      shopCar: carts,
    })
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()
  },
  // 数量加
  increat(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.shopCar;
    let num = carts[index].num;
    num = num + 1;
    carts[index].num = num;
    this.setData({
      shopCar: carts,
    })
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()
  },
  // 删除购物车当前商品
  delCurCart(e) {
    const id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let that = this;
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/shoppingCarDelete?token=3c35c3d0738a879f23926f4676b2874e',
      method: "POST",
      data: {
        shopping_car_id: id,
      },
      success: function (res) {
        console.log(res)
      }
    })
    let carts = this.data.shopCar;
    carts.splice(index, 1)
    that.setData({
      shopCar: carts
    })
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()
  },
  // 判断全选
  judgeSelected() {
    
    this.data.selectedAllStatus = this.data.shopCar.every((item) => {
      return item.selected;
    })&&this.data.shopCar.length>0;
    this.setData({selectedAllStatus:this.data.selectedAllStatus});

  },
  // 全选/全不选
  selectedAll(e) {
    let selectAll = this.data.selectedAllStatus;
    selectAll = !selectAll;
    let carts = this.data.shopCar;
    if (selectAll === true) {
      for (let i = 0; i < carts.length; i++) {
        let temp = carts[i];
        temp.selected = true;
      }
    } else {
      for (let i = 0; i < carts.length; i++) {
        let temp = carts[i];
        temp.selected = false;
      }
    }
    this.setData({
      shopCar: carts,
      selectedAllStatus: selectAll
    })
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()
  },
  // 选中当前商品
  curGood(e) {
    let carts = this.data.shopCar;
    let index = e.currentTarget.dataset.index;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      shopCar: carts
    })
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()
  },
  // 购买的商品
  PayGood() {
    let goods = this.data.payShop;
    goods = [];
    let carts = this.data.shopCar;
    for (let i = 0; i < carts.length; i++) {
      let temp = carts[i];
      if (temp.selected) {
        goods.push(temp);
        console.log(goods)
      }
    }
    this.setData({
      payShop: goods,
      shopCar: carts
    })
  },
  // 计算总价
  getTotalPrice() {
    let carts = this.data.shopCar;
    let total = 0;
    let totalNum = 0;
    let totalDisCount = 0;
    for (let i = 0; i < carts.length; i++) {
      let temp = carts[i];
      console.log(temp)
      if (temp.selected) {
        total += temp.num * temp.price;
        totalNum += temp.num ;
        totalDisCount += Number(temp.money)
      }
    }
    this.setData({
      totalPrice: total.toFixed(2),
      totalNum: totalNum,
      totalDisCount:totalDisCount.toFixed(2)
    })
  },
  // 去地图页
  toMap() {
    wx.navigateTo({
      url: '/components/map/map',
    })
  },
  //手指触摸动作开始 记录起点X坐标

  touchstart: function (e) {
    //开始触摸时 重置所有删除

    this.data.shopCar.forEach(function (v, i) {
      if (v.isTouchMove)//只操作为true的

        v.isTouchMove = false;

    })

    this.setData({
      startX: e.changedTouches[0].clientX,

      startY: e.changedTouches[0].clientY,

      shopCar: this.data.shopCar

    })

  },

  //滑动事件处理

  touchmove: function (e) {
    var that = this,

      index = e.currentTarget.dataset.index,//当前索引

      startX = that.data.startX,//开始X坐标

      startY = that.data.startY,//开始Y坐标

      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标

      touchMoveY = e.changedTouches[0].clientY,//滑动变化坐标

      //获取滑动角度

      angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });

    that.data.shopCar.forEach(function (v, i) {
      v.isTouchMove = false

      //滑动超过30度角 return

      if (Math.abs(angle) > 30) return;

      if (i == index) {
        if (touchMoveX > startX) //右滑

          v.isTouchMove = false

        else //左滑

          v.isTouchMove = true

      }

    })

    //更新数据

    that.setData({
      shopCar: that.data.shopCar

    })

  },

  /**
  
  * 计算滑动角度
  
  * @param {Object} start 起点坐标
  
  * @param {Object} end 终点坐标
  
  */

  angle: function (start, end) {
    var _X = end.X - start.X,

      _Y = end.Y - start.Y

    //返回角度 /Math.atan()返回数字的反正切值

    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);

  },
  // 删除多个商品
  delMulit() {

    this.data.shopCar.forEach((item)=>{
      if(item.selected){
        wx.request({
          url: 'http://api_devs.wanxikeji.cn/api/shoppingCarDelete?token=3c35c3d0738a879f23926f4676b2874e',
          method: "POST",
          data: {
            shopping_car_id: item.shopping_car_id,
          },
          success: function (res) {
            console.log(res)
          }
        })
      }
    })

    this.data.shopCar = this.data.shopCar.filter((item)=>{
      return !item.selected;
    })
    this.initData()
    
    
    this.getTotalPrice();
    this.PayGood();
    this.judgeSelected()

  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 初始化数
  initData() {
    this.setData(this.data);
  },
  onLoad: function (e) {
    let that = this;
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/shoppingCarList?token=3c35c3d0738a879f23926f4676b2874e',
      method: "POST",
      success: function (res) {
        let shopcar = res.data.data.data;
        console.log(res.data.data.data)
        shopcar = shopcar.map((item) => {
          item.selected = false;
          item.sku = JSON.parse(item.sku)

          return item;
        });
        that.setData({
          shopCar: shopcar
        })
      }
    })
    console.log(this.data.shopCar)
    this.judgeSelected();
  },
  
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log(this.data.storeAddress);
    // 配合自定义tabBar切换
    this.onLoad();
    if (typeof this.getTabBar === "function" && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3,
      });
    };
    //懒加载区域数据
    let that = this;
    wx.request({
      url: 'http://api_devs.wanxikeji.cn/api/goodList',
      method: "post",
      success: function (res) {
        that.setData({ listData: res.data.data.data });
      },

    })
    this.judgeSelected();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () { },
});
